<template>
	<el-card style="width: 80%; margin-left: 10%; height: 89vh;">

		<!-- 标签页 -->
		<el-tabs v-model="activeTab">
			<!-- 基本信息标签页 -->
			<el-tab-pane label="基本信息" name="basic">
				<!--编辑信息按钮位置-->
				<div style="display: flex; justify-content: flex-end; margin-bottom: 20px;">
					<el-button v-if="!isEditing" type="primary" @click="startEdit">
						编辑信息
					</el-button>
				</div>



				<el-form ref="formRef" :model="userInfo" :rules="isEditing ? formRules : {}" label-width="100px"
					style="padding-right: 70px;">
					<!-- 头像 -->
					<el-form-item label="头像" prop="avatar">
						<div style="width: 120px; height: 120px; overflow: hidden;">
							<el-upload list-type="picture-card" :auto-upload="false" action="#" :limit="1" :file-list="fileList"
								:on-change="uploadFile" :on-remove="removeFile" :disabled="isEditing">
							</el-upload>
						</div>
					</el-form-item>

					<!-- 姓名 -->
					<el-form-item label="姓名" prop="name">
						<el-input v-model="userInfo.name" :disabled="!isEditing" placeholder="请输入姓名">
						</el-input>
					</el-form-item>

					<!-- 电子邮箱 -->
					<el-form-item label="电子邮箱" prop="email">
						<el-input v-model="userInfo.email" :disabled="!isEditing" placeholder="请输入电子邮箱" type="email">
						</el-input>
					</el-form-item>

					<!-- 部门 -->
					<el-form-item label="部门" prop="department">
						<el-select v-model="userInfo.department" :disabled="!isEditing" placeholder="请选择部门" style="width: 100%">
							<el-option label="技术部" value="技术部"></el-option>
							<el-option label="产品部" value="产品部"></el-option>
							<el-option label="运营部" value="运营部"></el-option>
							<el-option label="市场部" value="市场部"></el-option>
							<el-option label="人力资源" value="人力资源"></el-option>
							<el-option label="财务部" value="财务部"></el-option>
							<el-option label="客服部" value="客服部"></el-option>
							<el-option label="行政部" value="行政部"></el-option>
							<el-option label="销售部" value="销售部"></el-option>
							<el-option label="设计部" value="设计部"></el-option>
							<el-option label="质量保证" value="质量保证"></el-option>
							<el-option label="法务部" value="法务部"></el-option>
							<el-option label="采购部" value="采购部"></el-option>
							<el-option label="信息安全" value="信息安全"></el-option>
							<el-option label="研发部" value="研发部"></el-option>
							<el-option label="客户成功" value="客户成功"></el-option>
							<el-option label="基础设施" value="基础设施"></el-option>
							<el-option label="教务部" value="教务部"></el-option>
						</el-select>
					</el-form-item>

					<!-- 工号 -->
					<el-form-item label="工号" prop="employeeId">
						<el-input v-model="userInfo.employeeId" :disabled="true" placeholder="工号（不可修改）">
						</el-input>
					</el-form-item>

					<!-- 手机号 -->
					<el-form-item label="手机号" prop="phone">
						<el-input v-model="userInfo.phone" :disabled="!isEditing" placeholder="请输入手机号" maxlength="11">
						</el-input>
					</el-form-item>

					<!-- 操作按钮区域 -->
					<el-form-item v-if="isEditing" style="margin-top: 30px;">
						<el-button @click="cancelEdit">取消</el-button>
						<el-button type="primary" @click="saveUserInfo" :loading="saving">
							保存修改
						</el-button>
					</el-form-item>


				</el-form>
			</el-tab-pane>

			<!-- 修改密码标签页 -->
			<el-tab-pane label="修改密码" name="password">
				<el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px"
					style="padding-right: 70px; max-width: 500px;">
					<!-- 原密码 -->
					<el-form-item label="原密码" prop="oldPassword">
						<el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入原密码" show-password>
						</el-input>
					</el-form-item>

					<!-- 新密码 -->
					<el-form-item label="新密码" prop="newPassword">
						<el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password>
						</el-input>
					</el-form-item>

					<!-- 确认密码 -->
					<el-form-item label="确认密码" prop="confirmPassword">
						<el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password>
						</el-input>
					</el-form-item>

					<!-- 操作按钮 -->
					<el-form-item style="margin-top: 30px;">
						<el-button type="primary" @click="changePassword" :loading="passwordSaving">
							确认修改
						</el-button>
						<el-button @click="resetPasswordForm">
							重置
						</el-button>
					</el-form-item>
				</el-form>
			</el-tab-pane>
		</el-tabs>
	</el-card>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { get, post } from '@/axios'
import router from '@/router'


//响应式数据
const formRef = ref()

//默认头像
const src = ref('/static/3e9ce3813b7199ea9588eeb920f41208_512_512.png')

// 当前活跃标签页
const activeTab = ref('basic')

// 基本信息编辑状态
const isEditing = ref(false)
const saving = ref(false)

// 密码修改状态
const passwordSaving = ref(false)
const passwordFormRef = ref()


// 用户信息
const userInfo = reactive({
	id: null,
	avatar: '',
	name: '',
	email: '',
	department: '',
	employeeId: '',
	phone: ''
})

//表单验证规则
const formRules = computed(() => {
	return {
		name: [
			{ required: true, message: '请输入姓名', trigger: 'blur' },
			{ min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
		],
		email: [
			{ required: true, message: '请输入邮箱地址', trigger: 'blur' },
			{ type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' },
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback()
						return
					}
					// 编辑模式下，如果邮箱没变化，不需要检查
					const originalEmail = originalUserInfo.email || ''
					if (isEditing.value && value === originalEmail) {
						callback()
						return
					}

					checkFieldUnique('email', value)
						.then(isUnique => {
							if (isUnique) {
								callback()
							} else {
								callback(new Error('邮箱已被其他管理员使用'))
							}
						})
						.catch(() => {
							callback(new Error('检查邮箱唯一性失败'))
						})
				},
				trigger: 'blur'
			}
		],
		department: [
			{ required: true, message: '请选择部门', trigger: 'change' }
		],
		phone: [
			{ required: true, message: '请输入联系电话', trigger: 'blur' },
			{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback()
						return
					}
					// 编辑模式下，如果手机号没变化，不需要检查
					const originalPhone = originalUserInfo.phone || ''
					if (isEditing.value && value === originalPhone) {
						callback()
						return
					}

					checkFieldUnique('phone', value)
						.then(isUnique => {
							if (isUnique) {
								callback()
							} else {
								callback(new Error('手机号已被其他人使用'))
							}
						})
						.catch(() => {
							callback(new Error('检查手机号唯一性失败'))
						})
				},
				trigger: 'blur'
			}
		]
	}
})

//唯一性校验
const checkFieldUnique = async (filedName, filedValue) => {
	const params = {
		filedName: filedName,
		filedValue: filedValue
	}
	try {
		const response = await get("/umsAdmin/checkUnique", params)
		return !response
	} catch (error) {
		console.error('检查唯一性失败:', error)
		return false
	}

}

// 备份原始数据（用于取消编辑时恢复）
const originalUserInfo = reactive({})

// 文件列表
const fileList = reactive([])

// 密码表单
const passwordForm = reactive({
	oldPassword: '',
	newPassword: '',
	confirmPassword: ''
})

// 密码表单验证规则
const passwordRules = {
	oldPassword: [
		{ required: true, message: '请输入原密码', trigger: 'blur' }
	],
	newPassword: [
		{ required: true, message: '请输入新密码', trigger: 'blur' },
		{ min: 6, max: 20, message: '密码长度应为6-20位', trigger: 'blur' }
	],
	confirmPassword: [
		{ required: true, message: '请再次输入新密码', trigger: 'blur' },
		{
			validator: (rule, value, callback) => {
				if (value !== passwordForm.newPassword) {
					callback(new Error('两次输入的密码不一致'))
				} else {
					callback()
				}
			},
			trigger: 'blur'
		}
	]
}

//获取用户信息
getUserInfo()
function getUserInfo() {
	get('/umsAdmin/getUserInfo', {}, content => {
		console.dir(content)
		userInfo.name = content.name,
			userInfo.email = content.email,
			userInfo.department = content.department,
			userInfo.employeeId = content.employeeId,
			userInfo.phone = content.phone,
			userInfo.avatar = content.avatar
		console.dir(content.avatar)
		if (content.avatar) {
			src.value = 'http://10.25.133.21:9000' + content.avatar
		}
		fileList.push({
			url: src.value
		})
	})
}


// 开始编辑
const startEdit = () => {
	isEditing.value = true
	// 备份原始数据
	Object.assign(originalUserInfo, userInfo)
}

// 取消编辑
const cancelEdit = () => {
	isEditing.value = false
	// 恢复原始数据
	getUserInfo()
	ElMessage.info('已取消编辑')
}

// 保存用户信息
const saveUserInfo = async () => {
	if (!isEditing.value) return;
	saving.value = true

	try {
		const submitData = {
			name: userInfo.name,
			email: userInfo.email,
			department: userInfo.department,
			phone: userInfo.phone
			// 工号employeeId不可编辑，无需传递
		}
		post('/umsAdmin/updateUserInfo', submitData, content => {
			isEditing.value = false
			ElMessage.success('保存成功！')
			getUserInfo()
		})
	} catch (error) {
		console.error('保存用户信息出错：', error);
		ElMessage.error('网络异常，保存失败请重试');
	} finally {
		saving.value = false
	}
}

// 修改密码
const changePassword = async () => {
	if (!passwordFormRef.value) return

	await passwordFormRef.value.validate((valid) => {
		if (valid) {
			submitPasswordChange()
		}
	})
}

// 提交密码修改
const submitPasswordChange = async () => {
	passwordSaving.value = true
	const submitData = {
		oldPassword: passwordForm.oldPassword,
		newPassword: passwordForm.newPassword
	}
	try {
		post("/umsAdmin/updatePassword", submitData).then(content => {
			resetPasswordForm()
			ElMessage.success('密码修改成功,请重新登录')

			setTimeout(() => {
				sessionStorage.clear()
				router.push('/')
			}, 1000)

		})
	} catch (error) {
		ElMessage.error('密码修改失败，请重试')
	} finally {
		passwordSaving.value = false
	}
}

// 重置密码表单
const resetPasswordForm = () => {
	passwordForm.oldPassword = null
	passwordForm.newPassword = null
	passwordForm.confirmPassword = null
	if (passwordFormRef.value) {
		passwordFormRef.value.clearValidate()
	}
}

// 上传文件
function uploadFile(file) {
	ElMessageBox.confirm('确定要保存该图片为用户头像吗？', '上传头像', {
		type: 'warning',
		cancelButtonText: '取消',
		confirmButtonText: '确定'
	}).then(() => {
		post('/umsAdmin/updateIcon', { file: file.raw }, content => {
			console.dir(content)
		})
	}).catch(() => { })

}

// 移除文件
const removeFile = () => {
	userInfo.avatar = null
	console.log('移除文件')

}
</script>

<style scoped lang="scss">
.el-card {
	:deep(.el-card__header) {
		background-color: #f5f7fa;
		border-bottom: 1px solid #e4e7ed;
	}

	:deep(.el-form-item__label) {
		font-weight: 500;
		color: #606266;
	}

	:deep(.el-input:not(.is-disabled) .el-input__wrapper) {
		box-shadow: 0 0 0 1px #dcdfe6 inset;

		&:hover {
			box-shadow: 0 0 0 1px #c0c4cc inset;
		}

		&.is-focus {
			box-shadow: 0 0 0 1px #409eff inset;
		}
	}

	:deep(.el-input.is-disabled .el-input__wrapper) {
		background-color: #f5f7fa;
		border-color: #e4e7ed;
		color: #c0c4cc;
	}

	:deep(.el-select.is-disabled .el-select__wrapper) {
		background-color: #f5f7fa;
		border-color: #e4e7ed;
		color: #c0c4cc;
	}

	:deep(.el-upload--picture-card) {
		width: 120px;
		height: 120px;
		border-radius: 8px;
	}

	:deep(.el-upload-list--picture-card .el-upload-list__item) {
		width: 120px;
		height: 120px;
		border-radius: 8px;
	}

	:deep(.el-tabs__item) {
		font-size: 16px;
		font-weight: 500;
	}

	:deep(.el-tabs__content) {
		padding-top: 20px;
	}
}
</style>